package com.dianjing.dianqun.common.interceptor;


import java.lang.invoke.MethodHandle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dianjing.dianqun.common.base.BaseRestController;
import com.dianjing.dianqun.common.exception.ExceptionResponse;
import com.dianjing.dianqun.common.thread.ThreadSaveLog;
import com.dianjing.dianqun.utils.Exceptions;

/**
 * 项目的 日志拦截器
 * @author baoyongtao
 *
 */

public class LogInterceptor implements HandlerInterceptor {
	private final static Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		/*if (!(handler instanceof HandlerMethod)) {
			return;
		} 
		HandlerMethod hMethod = (HandlerMethod)handler;
		MethodParameter[] parameters = hMethod.getMethodParameters();
		for (MethodParameter methodParameter : parameters) {
			 System.out.println(methodParameter.getParameterName());
		}*/
		// 有异常 需要通知
		if (ex != null) {
			// 可以用mq来通知异常信息
			LOG.info("发生错误了  块去看看！！！！！");
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			ExceptionResponse exceptionResponse = new ExceptionResponse(Exceptions.getStackTraceAsString(ex),
					ex.getClass().getSimpleName(),ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.getWriter().println(BaseRestController.mapper.writeValueAsString(exceptionResponse));
		}
		// 异步保存日志
		ThreadSaveLog.saveLog(request, handler, ex, null);
	}

}
